﻿using System;
using System.Collections.Generic;

// 气象数据类
public class WeatherData
{
    public DateTime LastCollectionTime { get; set; }
    public double Temperature { get; set; }
    public double Humidity { get; set; }
}

// 观察者接口
public interface IObserver
{
    void Update(WeatherData data);
}

// 主题接口
public interface ISubject
{
    void RegisterObserver(IObserver observer);
    void RemoveObserver(IObserver observer);
    void NotifyObservers();
}

// 气象站类
public class WeatherStation : ISubject
{
    private List<IObserver> observers;
    private WeatherData weatherData;

    public WeatherStation()
    {
        observers = new List<IObserver>();
        weatherData = new WeatherData();
    }

    public void RegisterObserver(IObserver observer)
    {
        observers.Add(observer);
    }

    public void RemoveObserver(IObserver observer)
    {
        observers.Remove(observer);
    }

    public void NotifyObservers()
    {
        foreach (var observer in observers)
        {
            observer.Update(weatherData);
        }
    }

    // 数据更新方法
    public void SetMeasurements(double temperature, double humidity)
    {
        weatherData.Temperature = temperature;
        weatherData.Humidity = humidity;
        weatherData.LastCollectionTime = DateTime.Now;

        Console.WriteLine($"气象数据已更新: 温度{temperature}°C, 湿度{humidity}%");
        NotifyObservers();  // 通知所有观察者
    }

    public WeatherData GetWeatherData()
    {
        return weatherData;
    }
}

// 屏幕显示类
public class ScreenDisplay : IObserver
{
    public void Update(WeatherData data)
    {
        Console.WriteLine($"[屏幕显示] 时间:{data.LastCollectionTime:HH:mm:ss} 温度:{data.Temperature}°C 湿度:{data.Humidity}%");
    }
}

// 数据库保存类
public class DatabaseSaver : IObserver
{
    public void Update(WeatherData data)
    {
        Console.WriteLine($"[数据库保存] 已保存数据: {data.LastCollectionTime:yyyy-MM-dd HH:mm:ss}, {data.Temperature}°C, {data.Humidity}%");
    }
}

// 测试程序
class Program
{
    static void Main(string[] args)
    {
        WeatherStation station = new WeatherStation();

        // 创建观察者
        ScreenDisplay screen = new ScreenDisplay();
        DatabaseSaver database = new DatabaseSaver();

        // 注册观察者
        station.RegisterObserver(screen);
        station.RegisterObserver(database);

        // 模拟数据更新
        station.SetMeasurements(25.5, 60.2);
        station.SetMeasurements(26.8, 58.7);
        station.SetMeasurements(24.2, 62.1);
    }
}